/**
 * 财务中心 - 收支对账
 */
define(function (require, exports, module) {
    var $ = require("jquery");
    require("pagination");
    var angular = require("angular");
    require("angular-ui");
    var util = require("util");
    var ui = require("ui");
    var dialog = require("dialog");
    var datepicker = require("datepicker");
    require("angular-interceptor"); // 接管 ajax 错误处理
    require('authorize');
    require("permission");
    require("/static_public/js/angular_directive/clipboard");
    require('global');

    var app = angular.module('app', ['ngUI', 'ngInterceptor', 'angular.directive.clipboard']);
    var api_prefix = G_CONFIG["api_prefix"] + "qmyx/game-rules/"; //api前缀
    var token = util.getToken();

    // 查询服务
    function filterService($http) {
        var service = {
            // 起始时间
            startDate: '',
            // 结束时间
            endDate: '',
            json: {},
            data:[],
            hasData: true,
            pageIndex: 1,
            total : 0,
            // 搜索关键字
            searchValue: "",
            // 查询参数
            queryParam: {},
            doQuery: function (pageIndex) {
                service.pageIndex = service.queryParam.pageIndex = pageIndex || 1;
                service.queryParam.pageSize = service.pageSize;
                var url = api_prefix + 'get-rule-list&token='+ token;
                $http.post(url, this.queryParam)
                        .success(function (data) {
                            if (data.retCode == 0) {
                                service.json = data.data;
                                service.data = data.data.list;
                                service.total = parseInt(data.data.count);
                                service.hasData = (data.data.count === "0") ? false :true;
                            } else {
                                ui.showErrTip(data.errMsg);
                                return false;
                            }
                        })
            },
            // 通过关键字查询
            searchData: function () {
                var filters = service.queryParam;
                filters.ruleName = this.searchValue;
                filters.pageIndex = 1;
                filters.startTime = this.startDate;
                filters.endTime = this.endDate;
                this.doQuery();
            },
            // 普通查询
            queryData: function () {
                var _this = this;
                this.queryParam = {
                    pageIndex: _this.pageIndex,
                    pageSize: _this.pageSize,
                    ruleName: _this.searchValue,
                    startTime: _this.startDate,
                    endTime: _this.endDate
                };
                this.doQuery();
            },

            // 控制游戏(开始/暂停/删除)
            ctrlGame: function(data, type){
                var link = "", msg="";
                switch (type){
                    case "start":
                      link = "restart-rule";
                      msg="规则开始，后续到达设置的业务节点会推送游戏，确认开始？";
                      break;
                    case "pause":
                      link = "pause-rule";
                      msg="规则暂停，后续到达业务节点不会推送游戏，确认暂停？";
                      break;
                    default: 
                      link = "delete-rule";
                      msg="规则删除，后续到达业务节点不会推送游戏，确认删除？";
                }
                util.confirm(msg, {
                    ok: function () {
                        var url = api_prefix + link;
                        $http.post(url, { ruleId: data.id})
                            .success(function (data) {
                                if (data.retCode == 0) {
                                    service.doQuery()
                                } else {
                                    ui.showErrTip(data.errMsg);
                                    return false;
                                }
                            });
                    }
                });
            }


        }
        return service;
    }
    app.factory('filters', ['$http', filterService]);

    function queryService($scope, $http, filters) {
        $scope.query = filters;
        setTimeout(function() {
            filters.queryData();
        }, 0);

        $scope.queryDataBySearch = function () {
            filters.searchData();
        };

        //显示详情对话框
        $scope.initEditGameDialog = function ($data, dialog, dialogScope, record) {
            dialogScope.data = $data;
            // 新增时获取项目列表
            var url = api_prefix + 'get-project-list';
            var ruleId = $data.id ? $data.id : "";
            var param = {
                ruleId: ruleId,
                token: token
            }
            $http.get(url, {params:param})
                .success(function (json) {
                    if (json.retCode == 0) {
                        record.projectList = dialogScope.data.projectList = json.data;
                        $data.project = $data.project || [];
                        record.projectId = dialogScope.data.projectId = getProjectVal($data.project);
                    } else {
                        ui.showErrTip(json.errMsg);
                    }

                })
            // 获取绑定项目的id, 将[{p_projectId:"555",ProjName:"aaa"}]转成["555","666"]
            function getProjectVal(arr){
                var newArr = []
                for (var i = 0, len = arr.length; i < len; i++) {
                    newArr.push(arr[i]["p_projectId"])
                };
                return newArr;
            };
        };
        $scope.save = function (record, dialog, dialogScope) {
            var url = api_prefix + 'add-rule';
            var param = {}, ruleToGameArr=[], ruleToConditionArr=[], ruleTargetProArr=[];
            var hasSetGame = false, bool = false;
            param.ruleTargetToken = token;
            param.ruleSettingName = record.ruleSettingName;
            param.ruleState = record.ruleState || 1;
            if (record.id ) {
                param.id = record.id;
            }else{
                param.id = "";
            }

            // 组合游戏类型和id:  
            //ruleToGame: "1:gameType:gameId,2:gameType:gameId"
            //ruleToCondition: "1:1,2:10,3:1"
            for (var i = 1; i <= 7; i++) {
                var set = "set"+i;
                if(record[set] && record[set]["display"] && record[set]["display"] === 1){
                    if(record[set]["gameName"]){
                        var ruleToGameStr = i + ":" + record[set].gameType + ":" + record[set].gameId;
                        ruleToGameArr.push(ruleToGameStr);
                        var baseC = record[set].baseCount ? record[set].baseCount : "1";
                        var ruleToConditionStr = i + ":" + baseC;
                        ruleToConditionArr.push(ruleToConditionStr);
                        hasSetGame = true;
                    }
                }
            };
            param.ruleToGame = ruleToGameArr.join(",");
            param.ruleToCondition = ruleToConditionArr.join(",");
            
            //验证游戏编辑
            function checkGame() {
                if(!record.ruleSettingName){
                    util.alert("请输入游戏规则名称");
                    return false;
                }else if(!hasSetGame){
                    util.alert("请至少设置一个游戏节点");
                    return false;
                }else if(record.projectId.length < 1){
                    util.alert("请至少绑定一个项目");
                    return false;
                }else{
                    return true;
                }
            };
            bool = checkGame();
            if(bool){
                param.ruleTargetPro = record.projectId.join("||");
                $http.post(url, param)
                    .success(function (data) {
                        if (data.retCode == 0) {
                            filters.doQuery()
                        } else {
                            ui.showErrTip(data.errMsg);
                            return false;
                        }
                    });
            }else{
                return bool;
            }
        }
    };
    app.controller('queryService', ['$scope', '$http', 'filters', queryService])

    // 游戏列表
    function gameListService($http) {
        var service = {
            data:[],
            hasData: true,
            pageIndex: 1,
            total : 0,
            // 搜索关键字
            searchValue: "",
            // 游戏类型列表
            fieldList: [],
            // 默认游戏类型
            field: "guagua",
            // 存储选中的单个游戏数据
            getGameRecord: {},
            // 是否选择了游戏
            hasSelectGame: false,
            // 查询参数
            queryParam: {},
            doQuery: function (pageIndex) {
                service.pageIndex = service.queryParam.pageIndex = pageIndex || 1;
                service.queryParam.pageSize = service.pageSize;
                var url = api_prefix + 'get-game-list';
                $http.get(url, {params:service.queryParam})
                        .success(function (data) {
                            if (data.retCode == 0) {
                                service.data = data.data.data;
                                service.total = parseInt(data.data.total);
                                service.hasData = (data.data.total === "0") ? false :true;
                            } else {
                                ui.showErrTip(data.errMsg);
                                return false;
                            }

                        })
            },
            queryGameType: function (opType) {
                var url = api_prefix+ 'select-game-type'+'&opType='+ opType +'&token='+ token;
                $http.get(url)
                    .success(function (data) {
                        if (data.retCode == 0) {
                            service.fieldList = data.data;
                        } else {
                            ui.showErrTip(data.errMsg);
                            return false;
                        }

                    })
            },
            
            // 通过关键字查询
            queryDataBySearch: function () {
                var filters = service.queryParam;
                filters.name = this.searchValue;
                filters.pageIndex = 1;
                this.doQuery();
            },
            // 普通查询
            queryData: function () {
                this.queryParam = {
                    pageIndex: service.pageIndex,
                    pageSize: service.pageSize,
                    name: service.searchValue,
                    gameType: service.field,
                    token: token
                };
                this.doQuery();
            },
            // 改变游戏列表功能
            gameTypeChanged: function(){
                service.queryParam.gameType = service.field;
                service.queryParam.name = service.searchValue = "";
                service.hasSelectGame = false;
                this.doQuery();
            },
            // 获取选中的数据
            getRecord: function(record){
                service.getGameRecord = record;
                service.hasSelectGame = true;
            },
            bindEvent: function(){
                $("#gameList").on("click","tr",function(){
                    $(this).find("input")[0].click();
                });
            }
        }
        return service;
    }
    app.factory('gameList', ['$http', gameListService]);

    function selectGameCtrl($scope, $http, gameList) {
        //显示详情对话框
        $scope.selectGameDialog = function (record, dialog, dialogScope, count) {
            dialogScope.query = gameList;
            gameList.hasSelectGame = false;
            gameList.field = "guagua";
            gameList.name = "";
            setTimeout(function() {
                gameList.queryGameType(count);
                gameList.queryData();
                gameList.bindEvent();
            }, 0);
            dialogScope.getRecord = gameList.getRecord;
            dialogScope.query.gameTypeChanged = gameList.gameTypeChanged;

            dialogScope.aftercopy = function () {
                ui.showSucTip('复制成功');
            }
        };
        $scope.selectSave = function (record) {
            if(!gameList.hasSelectGame){
                
                util.alert("请选择一个游戏");
                return false;
            }else{
                angular.extend(record,gameList.getGameRecord);
                record.gameType = gameList.field
            }
        }
    };
    app.controller('selectGameCtrl', ['$scope', '$http', 'gameList', selectGameCtrl])

    angular.bootstrap(document, ['app']);
});